/**
 * 
 */
package org.intelligentsia.artifacts.repository.metadata.adapter;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import org.intelligentsia.artifacts.repository.metadata.Versioning;

/**
 * @author geronimo
 * 
 */
public class VersioningAdapter {

	public static Versioning read(JSONObject jsonObject) throws JSONException {
		Versioning versioning = null;
		if (jsonObject != null) {
			versioning = new Versioning();
			versioning.setLastUpdated(jsonObject.optString("lastUpdated"));
			versioning.setLatest(jsonObject.optString("latest"));
			versioning.setRelease(jsonObject.optString("release"));
			versioning.setSnapshot(SnapshotAdapter.read(jsonObject.optJSONObject("snapshot")));
			versioning.setSnapshotVersions(SnapshotVersionAdapter.read(jsonObject.optJSONArray("snapshotVersions")));
			versioning.setVersions(readVersions(jsonObject.optJSONArray("versions")));
		}
		return versioning;
	}

	public static JSONObject write(Versioning versioning) throws JSONException {
		JSONObject jsonObject = null;
		if (versioning != null) {
			jsonObject = new JSONObject();
			jsonObject.putOpt("lastUpdated", versioning.getLastUpdated());
			jsonObject.putOpt("latest", versioning.getLatest());
			jsonObject.putOpt("release", versioning.getRelease());
			jsonObject.putOpt("snapshot", SnapshotAdapter.write(versioning.getSnapshot()));
			jsonObject.putOpt("snapshotVersions",SnapshotVersionAdapter.write(versioning.getSnapshotVersions()));
			jsonObject.putOpt("versions", writeVersions(versioning.getVersions()));
		}
		return jsonObject;
	}
 

	private static List<String> readVersions(JSONArray jsonArray) {
		List<String> versions = null;
		if (jsonArray != null) {
			versions = new ArrayList<String>(jsonArray.length());
			for (int i = 0; i < jsonArray.length(); i++) {
				versions.add(jsonArray.optString(i));
			}
		}
		return versions;
	}

	private static JSONArray writeVersions(List<String> versions) throws JSONException {
		JSONArray jsonArray = null;
		if (versions != null) {
			jsonArray = new JSONArray();
			for(String version:versions) {
				jsonArray.put(version);
			}
		}
		return jsonArray;
	}
}
